package com.human.controller;

import com.human.dao.EmpsalaryMapper;
import com.human.entity.Empsalary;
import com.human.entity.EmpsalaryDto;
import com.human.entity.ResultVo;
import io.swagger.annotations.Api;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author jzq
 * @date 2023/3/23 15:47
 */
@SuppressWarnings({"all"})
@RestController
@RequestMapping("/api")
@Api(tags = "导出Excel")
public class ExportController {

    @Resource
    EmpsalaryMapper empsalaryMapper;

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 设置响应头，告诉浏览器这是一个Excel文件
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"empsalary.xlsx\"");
        // 创建Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 创建工作表
        XSSFSheet sheet = workbook.createSheet("empsalary");
        // 创建表头
        XSSFRow headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("姓名");
        headerRow.createCell(1).setCellValue("工资账套");
        headerRow.createCell(2).setCellValue("基本工资");
        headerRow.createCell(3).setCellValue("奖金");
        headerRow.createCell(4).setCellValue("午餐补助");
        headerRow.createCell(5).setCellValue("交通补助");
        headerRow.createCell(6).setCellValue("应发工资");
        // 添加数据
        List<EmpsalaryDto> list = empsalaryMapper.getAllEmpsalary();
        for (int i = 0; i < list.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            EmpsalaryDto dto = list.get(i);
            row.createCell(0).setCellValue(dto.getName());
            row.createCell(1).setCellValue(dto.getSalName());
            row.createCell(2).setCellValue(dto.getBasicSalary());
            row.createCell(3).setCellValue(dto.getBonus());
            row.createCell(4).setCellValue(dto.getLunchSalary());
            row.createCell(5).setCellValue(dto.getTrafficSalary());
            row.createCell(6).setCellValue(dto.getAllSalary());
        }
        // 写入到响应流中
        workbook.write(response.getOutputStream());
        // 关闭工作簿
        workbook.close();
    }


}
